package com.vertxsample.samples.testgateway.gatewayserver

import com.vertxsample.samples.core.web.GatewayHandler
import io.vertx.circuitbreaker.CircuitBreaker
import io.vertx.circuitbreaker.CircuitBreakerOptions
import io.vertx.core.AbstractVerticle
import io.vertx.core.Future
import io.vertx.core.Handler
import io.vertx.core.Vertx
import io.vertx.core.http.HttpServerOptions
import io.vertx.core.http.HttpServerResponse
import io.vertx.core.json.JsonObject
import io.vertx.core.net.JksOptions
import io.vertx.ext.consul.ConsulClient
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import io.vertx.ext.web.client.WebClient
import io.vertx.ext.web.handler.StaticHandler
import org.apache.logging.log4j.LogManager
import java.lang.Math.abs
import kotlin.random.Random


class StarterVerticle(
    val options: JsonObject,
    val port: Int,
    val consulClient: ConsulClient
) : AbstractVerticle() {
     val logger = LogManager.getLogger(StarterVerticle::class.java!!.getName())
    override fun start(startFuture: Future<Void>) {
        //启动web
        startServer(startFuture ,options);
    }

    fun  startServer(startFuture:Future<Void>,options :JsonObject){

        var router = Router.router(vertx)




        //配置网关路径

        router.route("/gateway/:nodeServerName/*").handler(GatewayHandler(vertx,consulClient))


        //静态页面配置
        val staticHandler = StaticHandler.create("src/main/webapp")
        router.route("/*").handler(staticHandler);

        //配置健康检查
        router.get("/health").handler({c -> c.response().html().end("success")})

        logger.info("server running on "+port)
        vertx.createHttpServer(
            HttpServerOptions()
                //.setLogActivity(true)
                .setSsl(true)
                .setKeyStoreOptions(JksOptions().setPath("gateway.jks").setPassword("214307815840192"))
                .setEnabledSecureTransportProtocols( setOf("TLSv1","TLSv1.1","TLSv1.2"))
                .addEnabledCipherSuite("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256")
                .addEnabledCipherSuite("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA")
                .addEnabledCipherSuite("TLS_ECDHE_RSA_WITH_RC4_128_SHA")
                .addEnabledCipherSuite("TLS_RSA_WITH_AES_128_CBC_SHA256")
                .addEnabledCipherSuite("TLS_RSA_WITH_AES_128_CBC_SHA")
                .addEnabledCipherSuite("SSL_RSA_WITH_RC4_128_SHA")
        ).requestHandler({ handler -> router.handle(handler)}).listen(port){ result ->
            if (result.succeeded()) {
                startFuture.complete()
            } else {
                logger.error("",result.cause())
                startFuture.fail(result.cause())
            }
        }
    }

    fun HttpServerResponse.html() : HttpServerResponse {
        return this.putHeader("content-type","text/html")
    }


}